last_order_id(0). // initial belief last_order_id become an internal record.

//added by Tony
// gets the price for the product,
// a random value between 100 and 110.
price(_Service,X) :- .random(R) & X = (5*R)+10.

plays(initiator,robot). 

/* Plans */

// send a message to the initiator introducing myself as a participant
+plays(initiator,In)
   :  .my_name(Me)
   <- .send(In,tell,introduction(participant,Me)).

// answer to Call For Proposal   
@c1 +cfp(CNPId,Task)[source(A)]
   :  plays(initiator,A) & price(Task,Offer)
   <- +proposal(CNPId,Task,Offer); // remember my proposal
      .send(A,tell,propose(CNPId,Offer)).
	  
@c2 +cfp(CNPId,Task)[source(A)]//if the cfp didn't come from the initiator then
//refuse the cfp.
	: ~plays(initiator,A)
	 <- .send(A,tell,refuse(CNPId)).
	 
@r1 +accept_proposal(CNPId)
   :  proposal(CNPId,Task,Offer)
   <- .print("My proposal '",Offer,"' won CNP ",CNPId,
             " for ",Task,"!");
			 !Task;
        	  ?plays(initiator,A);
			 .send(A,tell,completed_contract(CNPId)).
      // do the task and report to initiator
      
@r2 +reject_proposal(CNPId)
   <- .print("I lost CNP ",CNPId, ".");
      -proposal(CNPId,_,_,_). // clear memory
//existing stuff

// plan to achieve the goal "order" for agent Ag
+!order(Product,Qtd) //in this case the order must come from
//the supermarket itself.
  <- ?last_order_id(N);
     OrderId = N + 1;
     -+last_order_id(OrderId);
     deliver(Product,Qtd);
	 ?plays(initiator,A);
	 ?proposal(CNPId,Task,Offer);
	 .print("delivering on contract:",CNPId," which is order:",OrderId," for me.");
     .send(A, tell, delivered(Product,Qtd,CNPId)). //changed Ag to robot

